package ltd.dujiabao.inventoryservice.dao;

import ltd.dujiabao.inventoryservice.domain.entity.Inventory;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Bowie Du
 * @date 2025/7/12 18:08
 */
@Repository
public interface InventoryRepository extends CrudRepository<Inventory, Long> {

    @Modifying(clearAutomatically = true, flushAutomatically = true)
    @Transactional(rollbackFor = Exception.class)
    @Query("update Inventory set usedStock = usedStock + :quantity, updatedAt = now() " +
            "where productId = :productId and :quantity <= totalStock - usedStock")
    int deductStock(Long productId, Integer quantity);
}
